var revenueApi = require('../../script/revenue.js');
import {
  parseTime
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: '1',
    TaskName: '',
    AUDIT_ID: '',
    UnPlannCount: 0,
    PlannedCount: 0,
    planed: {
      CurrentPage: 1,
      PageSize: 20,
      dataList: [],
      HasNextPage: true,
      noData: false,
      isReachBottom: false,
    },
    unplaned: {
      CurrentPage: 1,
      PageSize: 20,
      dataList: [],
      HasNextPage: true,
      noData: false,
      isReachBottom: false,
    },
    SelectAll: false,
    handleType: 1,
    selectlist: [],
    showPop: false,
    minDate: new Date().getTime(),
    maxDate: new Date(2025, 12, 31).getTime(),
    currentDate: new Date().getTime(),
    reasonPop: false,
    Reason: '',
    searchPop: false,
    searchParams: {
      DEPT_PART: "",
      UserCode: '',
      UserName: '',
      ROOM: '',
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options) {
      this.setData({
        TaskName: options.name,
        AUDIT_ID: options.id,
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getUnPlanedList(true);
    this.getPlanedList(true);
    this.QueryTaskDetailCount();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  _refreshData() {
    this.setData({
      "unplaned.CurrentPage": 1,
      "unplaned.dataList": [],
      "unplaned.HasNextPage": true,
      "unplaned.noData": false,
      "unplaned.isReachBottom": false,
      "planed.CurrentPage": 1,
      "planed.dataList": [],
      "planed.HasNextPage": true,
      "planed.noData": false,
      "planed.isReachBottom": false,
      currentDate: new Date().getTime(),
      handleType: 1,
    });
    this.getUnPlanedList(true);
    this.getPlanedList(true);
    this.QueryTaskDetailCount();
  },
  tabChange(e) {
    this.setData({
      activeIndex: e.detail.name,
    })
    // this.getOrderList(true);
  },
  getUnPlanedList(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = {
      Data: JSON.stringify({
        AUDIT_ID: this.data.AUDIT_ID,
        CurrentPage: this.data.unplaned.CurrentPage,
        PageSize: this.data.unplaned.PageSize,
      }),
    }
    revenueApi.QueryTaskUnPlaned(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.DataList]
        } else {
          dataList = [...this.data.unplaned.dataList, ...res.data.DataList]
        }
        let HasNextPage = res.data.HasNextPage;
        const noData = dataList.length === 0
        this.setData({
          "unplaned.dataList": dataList,
          "unplaned.HasNextPage": HasNextPage,
          "unplaned.noData": noData
        })
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  loadmoreUnplaned() {
    this.setData({
      "unplaned.isReachBottom": true
    });
    if (this.data.unplaned.HasNextPage) {
      this.setData({
        "unplaned.CurrentPage": this.data.unplaned.CurrentPage + 1
      })
      this.getUnPlanedList();
    }
  },
  getPlanedList(isRefresh) {
    // wx.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    const params = {
      Data: JSON.stringify({
        AUDIT_ID: this.data.AUDIT_ID,
        CurrentPage: this.data.planed.CurrentPage,
        PageSize: this.data.planed.PageSize,
      }),
    }
    revenueApi.QueryTaskPlaned(params).then(res => {
      // wx.hideLoading();
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.DataList]
        } else {
          dataList = [...this.data.planed.dataList, ...res.data.DataList]
        }
        let HasNextPage = res.data.HasNextPage;
        const noData = dataList.length === 0
        this.setData({
          "planed.dataList": dataList,
          "planed.HasNextPage": HasNextPage,
          "planed.noData": noData
        })
      }
    }).catch(_err => {
      // wx.hideLoading();
    });
  },
  QueryTaskDetailCount() {
    const params = {
      Data: JSON.stringify({
        AUDIT_ID: this.data.AUDIT_ID,
      }),
    }
    revenueApi.QueryTaskDetailCount(params).then(res => {
      if (res.code === 200) {
        this.setData({
          UnPlannCount: res.data.UnPlannCount,
          PlannedCount: res.data.PlannedCount,
        })
      }
    }).catch(_err => {

    });
  },
  selectRow(e) {
    var row = e.currentTarget.dataset.row;
    const key = this.data.activeIndex == '1' ? 'unplaned.dataList' : 'planed.dataList';
    const dataList = this.data.activeIndex == '1' ? [...this.data.unplaned.dataList] : [...this.data.planed.dataList];
    const val = dataList.find(item => item.UserCode === row.UserCode);
    if (val.Selected && val.Selected == true) {
      val.Selected = false;
    } else {
      val.Selected = true;
    }
    this.setData({
      [key]: dataList
    });
  },
  CheckChange() {
    const flag = !this.data.SelectAll;
    const dataList = [...this.data.unplaned.dataList];
    dataList.forEach(item => {
      item.Selected = flag;
    });
    this.setData({
      'unplaned.dataList': dataList,
      SelectAll: flag
    });
  },
  getSelected() {
    const dataList = this.data.activeIndex == '1' ? [...this.data.unplaned.dataList] : [...this.data.planed.dataList];
    const list = [];
    dataList.forEach(item => {
      if (item.Selected && item.Selected == true) {
        list.push(item)
        // list.push(item.DETAIL_ID)
      }
    })
    return list;
  },
  CommonHandle(e) {
    var type = e.currentTarget.dataset.type;
    const list = this.getSelected();
    if (list.length === 0) {
      wx.showToast({
        title: '至少选择一条数据',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    this.setData({
      showPop: true,
      selectlist: list,
      handleType: type
    });
  },
  closePop() {
    this.setData({
      showPop: false,
      reasonPop: false
    });
  },
  onInput(e) {
    this.setData({
      currentDate: e.detail,
    });
  },
  onConfirm(e) {
    this.setData({
      showPop: false,
    });
    const timestamp = this.data.currentDate;
    if (this.data.handleType === '0') {
      // 申请延期
      if (timestamp < new Date(this.data.selectlist[0].END_DATE).getTime()) {
        wx.showToast({
          title: '任务未超期，选择日期在计划日期内',
          icon: 'none',
          duration: 1500
        });
        return;
      }
      this.setData({
        showPop: false,
        reasonPop: true,
      })
    } else {
      // 安排计划 重新计划
      if (timestamp > new Date(this.data.selectlist[0].END_DATE).getTime()) {
        wx.showToast({
          title: '不能超过结束日期' + this.data.selectlist[0].END_DATE_Str,
          icon: 'none',
          duration: 1500
        });
        return;
      }
      this.DoUpdate();
    }
  },
  DoUpdate() {
    const ids = [];
    this.data.selectlist.forEach(item => {
      if (item.Selected && item.Selected == true) {
        ids.push(item.DETAIL_ID)
      }
    })
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    const params = {
      Data: JSON.stringify({
        TaskDetailNos: ids.join(','),
        PlanDate: parseTime(this.data.currentDate),
      }),
    }
    revenueApi.UpdateTaskPlan(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        this._refreshData();
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 1500
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  inputChange(e) {
    this.setData({
      Reason: e.detail.value
    });
  },
  ReasonCancel() {
    this.setData({
      Reason: '',
      reasonPop: false
    });
  },
  ReasonConfirm() {
    if (this.data.Reason == '') {
      wx.showToast({
        title: '请输入延期原因',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    this.setData({
      reasonPop: false
    });
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    const ids = [];
    this.data.selectlist.forEach(item => {
      if (item.Selected && item.Selected == true) {
        ids.push(item.DETAIL_ID)
      }
    })
    const params = {
      Data: JSON.stringify({
        TaskDetailNos: ids.join(','),
        PlanDate: parseTime(this.data.currentDate),
        Reason: this.data.Reason
      }),
    }
    revenueApi.DeferTaskPlan(params).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        this._refreshData();
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none',
          duration: 1500
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
})